package user

import (
	"context"
	"errors"
	"strconv"
	"time"

	"api/common"
	"api/internal/svc"
	"api/internal/types"
	"api/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserInfo) (resp *types.TokenResponse, err error) {
	// 1. 校验参数
	if req.Name == "" || req.Mobile == "" || req.Email == "" || req.Password == "" {
		return nil, errors.New("参数错误")
	}

	var u *user.UserInfo

	// 2. 校验手机号是否存在
	if req.Mobile != "" {
		u, err = l.svcCtx.UserRPC.GetUserByMobile(l.ctx, &user.GetUserByMobileRequest{Mobile: req.Mobile})
		if err != nil {
			return nil, err
		}
		if u == nil || u.Id == 0 {
			return nil, errors.New("手机号不存在")
		}
	}
	// 3. 校验邮箱是否存在
	if req.Email != "" {
		u, err = l.svcCtx.UserRPC.GetUserByEmail(l.ctx, &user.GetUserByEmailRequest{Email: req.Email})
		if err != nil {
			return nil, err
		}
		if u == nil || u.Id == 0 {
			return nil, errors.New("邮箱不存在")
		}
	}

	// 4. 校验密码是否正确
	_, err = l.svcCtx.UserRPC.CheckPassword(l.ctx, &user.CheckPasswordRequest{
		Id:       u.Id,
		Password: req.Password,
	})
	if err != nil {
		return nil, err
	}

	secret := l.svcCtx.Config.Auth.AccessSecret
	expire := l.svcCtx.Config.Auth.AccessExpire
	token, err := common.GenerateJWTToken(strconv.Itoa(int(u.Id)), secret, expire)
	if err != nil {
		return nil, err
	}
	return &types.TokenResponse{
		Token:   token,
		Expires: time.Now().Add(expire * time.Second).Unix(),
	}, nil
}
